package com.easyj.admin.sys.controller;


import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.base.common.ajax.Result;
import com.easyj.base.common.export.ExpExcutor;
import com.easyj.base.common.export.ExpField;
import com.easyj.base.common.imp.ImpUtils;
import com.easyj.base.common.page.Page;
import com.easyj.base.common.page.PageFilter;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.admin.db.model.ImpResult;
import com.easyj.admin.db.model.Position;
import com.easyj.admin.db.model.Role;
import com.easyj.admin.db.model.User;
import com.easyj.admin.db.model.UserQO;
import com.easyj.admin.sys.service.DepartmentService;
import com.easyj.admin.sys.service.PositionService;
import com.easyj.admin.sys.service.RoleService;
import com.easyj.admin.sys.service.UserService;
	/**
	* 用户
	*
	 */
	@RestController
	@RequestMapping(value = "/sys/user")
	public class UserController extends BaseController{

		@Autowired
		private  UserService userService;
				
		@Autowired
		private  DepartmentService departmentService;
		
		@Autowired
		private  PositionService positionService;
		
		@Autowired
		private  RoleService roleService;
		
	
		/**
		 * get
		 * @param id
		 * @return
		 */
		@PreAuthorize("hasPermission('user','user:list')")
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	    	User entity = userService.findById(id);
	    	List<Role> roles=userService.findRolesByUserId(entity.getId());
	    	List<Long> rids=new ArrayList<Long>();
	    	if(roles!=null) {
		    	for(Role r:roles) {
		    		rids.add(r.getId());
		    	}
	    	}
	    	entity.setRoleIds(rids);
	    	
	    	List<Long> pids=new ArrayList<Long>();
	    	List<Position> positions=userService.findPositionsByUserId(id);
	    	if(positions!=null) {
		    	for(Position r:positions) {
		    		pids.add(r.getId());
		    	}
	    	}
	    	entity.setPositionIds(pids);	    	
	    	
	        return Result.Success(entity);
	    }
	    
		/**
		* 新增
		 * @throws EasyjException 
		*/
	    @PreAuthorize("hasPermission('user','user:add')")
		@RequestMapping(value = "add", method = RequestMethod.POST)
		public Result add(@RequestBody @Validated(User.Create.class) User entity,BindingResult validResult) throws EasyjException {
			if(validResult.hasErrors()){
				return Result.Error("数据不符合要求！");  
			}
								 
			userService.insertEntity(entity);
			return Result.Success();
			
		}
	    
	    private void preHandelFilter(UserQO filter) throws EasyjException {			
	  		if(filter.getDepartmentId()!=null) {
	  			List<Long> dptids=departmentService.getDesendantIds(filter.getDepartmentId(),false);
	  			if(dptids==null||dptids.size()==0) {
	  				throw new EasyjException(EasyjException.DataError,"数据错误，部门不存在！");	
	  			}else {
	  				filter.setDepartmentIds(dptids);
	  			}
	  		}
		}
		
		/**
		* 修改
		 * @throws EasyjException 
		*/
	    @PreAuthorize("hasPermission('user','user:edit')")
		@RequestMapping(value = "update", method = RequestMethod.POST)
		public Result update(@RequestBody @Validated(User.Update.class) User entity,BindingResult validResult) throws EasyjException {
			if(validResult.hasErrors()){
				return Result.Error("数据不符合要求！");  
			}					 
			userService.updateEntity(entity);
			return Result.Success();
			
		}

		/**
		* 分页查询
		* @param filter
		* @return
		 * @throws EasyjException 
		 */
	    @PreAuthorize("hasPermission('user','user:list')")
		@RequestMapping(value = "findPage", method = RequestMethod.POST)
		public Result findPage(@RequestBody  UserQO filter) throws EasyjException {
			preHandelFilter(filter);
			Page<User>  page =userService.findPage(filter);	
			return Result.Success(page);
		}
	    
	    /**
	     * 给前端按名称搜索用
	     */
		@RequestMapping(value = "searchUser", method = RequestMethod.POST)
		public Result searchUser(@RequestParam(value = "filter") String  filter)  {
			List<User>  page =userService.searchUser(filter);	
			return Result.Success(page);
		}
		
		/**
		* 停用
		* @param ids
		* @return
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('user','user:edit')")
		@RequestMapping(value = "disable", method = RequestMethod.GET)
		public Result disable(@RequestParam(value = "id") Long id) throws EasyjException{
			userService.disableById(id);
			return Result.Success();
			
		}
		
		/**
		 * 启用
		* @param id
		* @return
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('user','user:edit')")
		@RequestMapping(value = "enable", method = RequestMethod.GET)
		public Result enable(@RequestParam(value = "id") Long id) throws EasyjException{
			
			userService.enableById(id);
			return Result.Success();		
		}
		
		@PreAuthorize("hasPermission('user','user:edit')")
		@RequestMapping(value = "leave", method = RequestMethod.GET)
		public Result leave(@RequestParam(value = "id") Long id) throws EasyjException{
			userService.leaveById(id);
			return Result.Success();	
			
		}
		
		
		
		/** 解锁
		* @param id
		* @return
		*/
		@PreAuthorize("hasPermission('user','user:edit')")
		@RequestMapping(value = "unLocked", method = RequestMethod.GET)
		public Result unLocked(@RequestParam(value = "id") Long id){			 
			userService.unLockedUserById(id);
			return Result.Success();	
			
		}
		
		@PreAuthorize("hasPermission('user','user:edit')")
		@PostMapping(value = "/changePassword")
		public Result changePassword(@RequestBody User user) {
			if(user.getPassword()==null||user.getPassword().length()>18||user.getPassword().length()<6) {
				return Result.Error("密码不符合要求");
			}			
			//正则表达式，password数字与字母组成...			
			
			userService.changePassword(user);
			
			return Result.Success();
		}
		
		
		
		/**
		 *  下载导入模板
		 * @param response
		 */
		@PreAuthorize("hasPermission('user','user:add')")
		@RequestMapping(value = "exportTpl", method = RequestMethod.GET)
		public void exportTpl( HttpServletResponse response){
			try {
				//生成 excel
				SXSSFWorkbook workbook=ImpUtils.getImpTemplateExcel("user.xml","");
				//岗位下拉框
				SXSSFSheet sheet=workbook.getSheetAt(0);
				Position filter=new Position();
				List<Position> clist=positionService.findList(filter);
				if(clist!=null &&clist.size()>0) {
					String[] vs=new String[clist.size()]; 
					for(int i=0;i<clist.size();i++) {
						vs[i]=clist.get(i).getName();
					}
				  ImpUtils.createDropDownList(sheet, vs, 2, ImpUtils.XLS_MAX_ROW, 6, 6);
				}
				
				
				List<Role> rlist=roleService.findList(new Role());
				if(rlist!=null &&rlist.size()>0) {
					String[] vs=new String[clist.size()]; 
					for(int i=0;i<clist.size();i++) {
						vs[i]=rlist.get(i).getName();
					}
				  ImpUtils.createDropDownList(sheet, vs, 2, ImpUtils.XLS_MAX_ROW, 7, 7);
				}
				
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="用户导入模板"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			}catch (Exception ex) {
				log.error("UserController.exportTpl", ex);
			} 
		}		
		
		/**
		 * 导入
		 * 配合element upload 控件
	     * 直接  throw error
		 * @param file
		 * @return
		 * @throws Exception
		 */ 
		@PreAuthorize("hasPermission('user','user:add')")
		@RequestMapping(value = "importExcel", method = RequestMethod.POST)
		public Result importExcel(@RequestParam MultipartFile file) throws Exception{
			ImpResult rtn=userService.importExcel(file, SecurityUtil.getOperatorId());
			return Result.Success(rtn);
		}
      
     
		/**
		* 导出Excel
		* @param filter
		* @param expFields
		* @param response
		*/
		@PreAuthorize("hasPermission('user','user:list')")
		@RequestMapping(value = "export", method = RequestMethod.POST)
		public void export(@RequestBody UserQO filter, HttpServletResponse response){
			try {
				 //导出的字段		
				List<ExpField> fields = new ArrayList<ExpField>();
			      fields.add(new ExpField("loginName","账号"));
			      fields.add(new ExpField("name","姓名"));
			      fields.add(new ExpField("sex","性别","left","sexFormat"));
			      fields.add(new ExpField("departmentName","所属部门"));
			      fields.add(new ExpField("positionsName","岗位"));
			      fields.add(new ExpField("rolesName","拥有角色"));
			      fields.add(new ExpField("duty","职务"));
			      fields.add(new ExpField("jionday","入职日期","left","date"));
			      fields.add(new ExpField("mobile","手机号码"));
			      fields.add(new ExpField("telephone","联系电话"));
			      fields.add(new ExpField("email","email"));
			      fields.add(new ExpField("address","居住地址"));
			      fields.add(new ExpField("idNo","身份证号码",""));
			      //fields.add(new ExpField("idType","证件类型",""));
			      fields.add(new ExpField("birthday","出生日期",""));
			      fields.add(new ExpField("eduLevel","学历",""));
			      fields.add(new ExpField("gradeSchool","毕业院校",""));
			      fields.add(new ExpField("gradeDay","毕业时间",""));
			      fields.add(new ExpField("stateName","职位状态"));
			      fields.add(new ExpField("statusName","账号状态","left","statusFormat"));
			    
				//生成 excel
				SXSSFWorkbook workbook=exportExcel(filter, fields);
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="员工"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			} catch (Exception ex) {
				log.error("EmployeeController.export", ex);
			} 
		}
		
		/**
		* 导出excel,生成workbook 
		*/
		private SXSSFWorkbook exportExcel(final UserQO filter,List<ExpField> fields) {
			ExpExcutor<User>  expExcutor=new ExpExcutor<User>(){
				@Override
				protected Long getRecordCount() {
					return userService.count(filter);
				}

				@Override
				protected List<User> getSheetData(int sheetSize, int sheetinx) {
					PageFilter queryPage=new PageFilter(sheetSize,sheetinx+1);
					filter.setPage(queryPage);
					List<User> datas=null;
					datas = userService.findList(filter);
					if(datas!=null) {						
						for(User u:datas) {
							StringBuffer pf=new StringBuffer();
							StringBuffer rf=new StringBuffer();
							if(u.getRoles()!=null) {
								for(Role r:u.getRoles()) {
									rf.append(r.getName()).append(" ");
								}
							}
							if(u.getPositions()!=null) {
								for(Position r:u.getPositions()) {
									pf.append(r.getName()).append(" ");
								}
							}
							u.setRolesName(rf.toString());
							u.setPositionsName(pf.toString());
						}
						
					}
					
					return datas;
				}
			};
			SXSSFWorkbook workbook=expExcutor.export(fields,false);
			return workbook;
		}	
}

